package com.free4inno.knowledgems.service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.concurrent.*;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import  com.free4inno.knowledgems.service.FileService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.UUID;

@Slf4j
@Service
public class FileDownloadService {

    private final ExecutorService executorService;

    public FileDownloadService() {
        // 创建一个拥有10个线程的固定大小线程池（根据需要调整）
        this.executorService = Executors.newFixedThreadPool(10);
    }

    public void downloadFileAsync(String filename, String id, Boolean isImage, HttpServletResponse response) {
        // 提交下载任务给执行者服务
        Future<?> future = executorService.submit(() -> downloadFileThread(filename, id, isImage, response));


        // 如果需要，可以使用Future对象检查状态或在将来获取结果
    }

    public void shutdown() {
        // 当不再需要时关闭执行者服务
        executorService.shutdown();
    }

    public void downloadFileThread(String filename, String id, Boolean isImage, HttpServletResponse response) {
        log.info(this.getClass().getName() + "----in----" + "下载文件（downloadFileThread）" + "----");
//        String savePath = FileService.getSavePath();
//        String orginFilePath = savePath + "/" + id;
         String orginFilePath = "D://aaaajava//zhi//knowledgems//src//main//webapp//uploadfiles//1913211cac1247848471621d05a38b0d8593473563396304978.mp4";
        File file = new File(orginFilePath);
        System.out.println("文件:" + file);
        System.out.println("orginFilePath:" + orginFilePath);

        if (file.exists()) {
            try (InputStream inputStream = new FileInputStream(file);
                 BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {

                byte[] buffer = new byte[1024];
                int byteread;

                response.reset();
                if (isImage) {
                    // 图片直接输出到浏览器
                    String formatType = id.substring(id.lastIndexOf(".") + 1);
                    response.setContentType("image/" + formatType);
                } else {
                    // 附件执行下载任务
                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                    response.setContentType("application/octet-stream");
                }

                while ((byteread = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, byteread);
                }

                log.info(this.getClass().getName() + "----out----" + "文件下载完毕thread" + "----");

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            response.reset();
            try {
                response.sendError(404, "文件不存在");
                log.info(this.getClass().getName() + "----out----" + "文件不存在" + "----");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}